<template>
	<view class="container">
		<TopNav title="时间设置" bg-color="#F5F6F7"></TopNav>
		<view class="header">
			<view class="tabs">
				<view class="tabs-item" v-for="(item,index) in tabsList" :key="index"
					:class="{'tabs-item-active':tabsCurrent === index}" @click="handleTabsChange(item,index)">
					<text>{{item.text}}</text>
				</view>
			</view>
			<view class="card">
				<view class="line-h16 flex align-center">
					<view class=""
						style="width: 12rpx;height: 12rpx;border-radius: 4rpx;margin-right: 6rpx;background-color: #f37b1d;">
					</view>
					<text>黄色:设置的忙时时间，可以自由设置</text>
				</view>
				<view class="line-h16 flex align-center">
					<view class=""
						style="width: 12rpx;height: 12rpx;border-radius: 4rpx;margin-right: 6rpx;background-color: white;">
					</view>
					<text>白色:可以接单时间</text>
				</view>
				<view class="line-h16 flex align-center">
					<view class=""
						style="width: 12rpx;height: 12rpx;border-radius: 4rpx;margin-right: 6rpx;background-color: #FE3F59;">
					</view>
					<text>红色:订单预约时间，不可取消</text>
				</view>
			</view>
		</view>
		<view class="main">
			<view class="time-container" @touchstart="handleTouchStart" @touchmove="handleTouchMove"
				@touchend="handleTouchEnd">
				<view class="time-item" v-for="item in timeList" :key="item.text" @click="handleSelectTime(item)"
					:class="{'time-check':chenckTimeCheck(item),'time-disabled':item.type === 1}">
					<text>{{item.text}}</text>
				</view>
			</view>
			<view class="flex justify-center fixed-bottom">
				<view class="self-btn m-r10" style="background-color: #EBECED;width: 194rpx;" hover-class="pressed"
					@click="handleSelectAll">
					<image src="/static/images/index/radio-check.png" class="width-18 height-18" mode=""
						v-if="selectAll">
					</image>
					<image src="/static/images/index/radio.png" class="width-18 height-18" mode="" v-else></image>
					<text class="text-black m-l6">全选</text>
				</view>
				<view class="self-btn" style="width: 488rpx;" hover-class="pressed" @click="handleSubmit">
					<text>立即保存</text>
				</view>
			</view>
		</view>
		<Toast></Toast>
	</view>
</template>

<script>
	import {
		workTime,workTimeDada
	} from "@/api/index"
	import {
		setWorkTime
	} from "@/api/index/set"
	import dayjs from 'dayjs'
	export default {
		name: "",
		data() {
			return {
				isTouching: false,
				lastSelectedIndex: -1,
				touchStartY: 0,
				touchStartX: 0,
				isHorizontalSlide: false, // 新增标志位判断是否是水平滑动
				//////
				selectAll: false,
				selection: [],
				queryParams: {
					date: dayjs().format("YYYY-MM-DD")
				},
				tabsCurrent: 0,
				tabsList: [{
					text: '今天',
					date: dayjs().format("YYYY-MM-DD")
				}, {
					text: '明天',
					date: dayjs().add(1, 'day').format("YYYY-MM-DD")
				}, {
					text: '后天',
					date: dayjs().add(2, 'day').format("YYYY-MM-DD")
				}, {
					text: dayjs().add(3, 'day').format("MM-DD"),
					date: dayjs().add(3, 'day').format("YYYY-MM-DD")
				}, {
					text: dayjs().add(4, 'day').format("MM-DD"),
					date: dayjs().add(4, 'day').format("YYYY-MM-DD")
				}],
				timeList: []
			}
		},
		onLoad() {
			this.timeList = this.generateTimeSlots()
		},
		onShow() {
			this.getList()
		},
		watch: {
			selection: {
				deep: true,
				handler(list) {
					if (list.length) {
						let filterList = this.timeList.filter(ele => ele.type === 0)
						if (list.length === filterList.length) {
							this.selectAll = true
						} else {
							this.selectAll = false
						}
					} else {
						this.selectAll = false
					}

				}
			}
		},
		methods: {
			// 修改触摸处理方法，增加方向判断
			handleTouchStart(e) {
				const touch = e.touches[0]
				this.touchStartY = touch.clientY
				this.touchStartX = touch.clientX
				this.isTouching = true
				this.isHorizontalSlide = false
			},

			handleTouchMove(e) {
				if (!this.isTouching) return

				const touch = e.touches[0]
				const deltaX = Math.abs(touch.clientX - this.touchStartX)
				const deltaY = Math.abs(touch.clientY - this.touchStartY)

				// 判断滑动方向，只有当水平滑动距离大于垂直距离时才处理
				if (deltaX > deltaY && deltaX > 10) {
					this.isHorizontalSlide = true
					this.processTouch(touch)
				} else if (deltaY > deltaX && deltaY > 10) {
					// 垂直滑动时不处理，保持页面滚动
					this.isHorizontalSlide = false
				}
			},

			handleTouchEnd() {
				this.isTouching = false
				this.lastSelectedIndex = -1
				this.isHorizontalSlide = false
			},

			processTouch(touch) {
				if (!this.isHorizontalSlide) return

				const query = uni.createSelectorQuery().in(this)
				query.selectAll('.time-item').boundingClientRect(rects => {
					const touchX = touch.clientX
					const touchY = touch.clientY

					rects.forEach((rect, index) => {
						if (this.lastSelectedIndex === index) return
						if (
							touchX >= rect.left &&
							touchX <= rect.right &&
							touchY >= rect.top &&
							touchY <= rect.bottom
						) {
							this.lastSelectedIndex = index
							const item = this.timeList[index]
							this.handleSelectTime(item)
						}
					})
				}).exec()
			},
			generateTimeSlots() {
				const timeSlots = [];
				for (let hour = 0; hour < 24; hour++) {
					// 生成整点时间（如00:00, 01:00等）
					timeSlots.push({
						text: `${hour.toString().padStart(2, '0')}:00`,
						type: 0
					});
					// 生成半点时间（如00:30, 01:30等）
					timeSlots.push({
						text: `${hour.toString().padStart(2, '0')}:30`,
						type: 0
					});
				}
				return timeSlots;
			},
			handleSelectAll() {
				this.selectAll = !this.selectAll
				if (this.selectAll) {
					// 0代表空闲可选
					this.selection = this.timeList.filter(ele => ele.type === 0).map(item => item.text)
				} else {
					this.selection = []
				}
			},
			// 匹配是否选中
			chenckTimeCheck(val) {
				return this.selection.indexOf(val.text) !== -1
			},
			handleSelectTime(select) {
				if (select.type !== 0) return

				let index = this.selection.findIndex(item => item == select.text)
				if (index === -1) {
					this.selection.push(select.text)
				} else {
					this.selection.splice(index, 1)
				}
			},
			handleTabsChange(select, index) {
				if (this.tabsCurrent === index) return
				this.tabsCurrent = index
				this.queryParams.date = select['date']
				this.getList()
			},
			handleSubmit() {
				let date = this.queryParams.date
				let hour = this.selection.join(",")
				this.$modal.loading('保存中')
				setWorkTime({
					date,
					hour
				}).then(res => {
					this.$toast('已保存')
					this.$modal.closeLoading()
				})
			},
			getList() {
				workTimeDada(this.queryParams)
				workTime(this.queryParams).then(res => {
					let {
						data
					} = res
					// 选中值初始化
					this.selection = []
					for (let item of data) {
						// item.type  0：空闲 1：订单 2：忙时
						if (item.type === 2) {
							this.selection.push(item.hour)
						} else {
							let findIndex = this.timeList.findIndex(findItem => findItem.value === item.hour)
							// 设置对应状态
							if (findIndex !== -1) this.$set(this.timeList[findIndex], 'type', item.type)
						}

					}
				})
			}
		}
	}
</script>
<style lang="scss">
	@import '@/common/css/var.scss';

	page {
		@include fixed-bottom;
	}

	.header {
		position: sticky;
		@include sticky-top;
	}
</style>
<style scoped lang="scss">
	.container {
		padding: 0 24rpx;
		box-sizing: border-box;
		background-color: inherit;

		.header {
			background-color: inherit;
			padding-bottom: 10rpx;
			box-sizing: border-box;
		}

		.tabs {
			display: flex;
			justify-content: space-between;
			padding: 26rpx 0 20rpx 0;
			box-sizing: border-box;

			.tabs-item {
				border-radius: 32rpx;
				// width: 160rpx;
				height: 64rpx;
				padding: 0 32rpx;
				display: flex;
				justify-content: center;
				align-items: center;
				font-weight: 400;
				font-size: 24rpx;
				background-color: #fff;
				// margin-right: 20rpx;
			}

			.tabs-item-active {
				background-color: #121924;
				color: #fff;
			}
		}

		.card {
			background-color: #EBEDF0;
			border-radius: 12rpx;
			padding: 16rpx;
		}

		.main {
			.time-container {
				display: grid;
				grid-template-columns: repeat(4, 160rpx);
				grid-template-rows: repeat(4, 88rpx);
				grid-gap: 20rpx 20rpx;

				.time-item {
					// width: 160rpx;
					height: 88rpx;
					background-color: #fff;
					border-radius: 12rpx;
					text-align: center;
					line-height: 88rpx;
					box-sizing: border-box;
				}

				.time-check {
					border: 2rpx solid #f37b1d;
					background: rgba(243, 123, 29, 0.1);
					box-sizing: border-box;
				}

				.time-disabled {
					background: #FEEBEE;
					border: 2rpx solid #FE3F59;
					box-sizing: border-box;
				}
			}
		}
	}

	/* 新增触摸反馈样式 */
	.active-feedback {
		transform: scale(0.95);
		opacity: 0.9;
	}
</style>